package com.xtc.netty.protocol.http.xml;

import com.xtc.netty.protocol.http.model.Order;
import com.xtc.netty.protocol.http.xml.codec.HttpXmlRequestDecoder;
import com.xtc.netty.protocol.http.xml.codec.HttpXmlResponseEncoder;
import com.xtc.netty.protocol.http.xml.handler.HttpXmlServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;

import java.net.InetSocketAddress;

public class HttpXmlServer {

    public void run(final int port) {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap server = new ServerBootstrap();
            server.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast("http-decoder", new HttpRequestDecoder())
                                    .addLast("http-aggregator", new HttpObjectAggregator(65536))
                                    .addLast("xml-decoder", new HttpXmlRequestDecoder(Order.class, true))
                                    .addLast("http-encoder", new HttpResponseEncoder())
                                    .addLast("xml-encoder", new HttpXmlResponseEncoder())
                                    .addLast("xmlServerHandler", new HttpXmlServerHandler());

                        }
                    });
            ChannelFuture future = server.bind(new InetSocketAddress(port)).sync();

            System.out.println("Http 订购服务已启动，服务地址:127.0.0.1" + port);

            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new HttpXmlServer().run(9090);
    }
}
